package com.zhao.reggie3.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhao.reggie3.common.R;
import com.zhao.reggie3.damain.User;
import com.zhao.reggie3.service.UserService;
import com.zhao.reggie3.utils.SMSUtils;
import com.zhao.reggie3.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: zhao
 * @time: 2022/8/22 11:00
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * @description 发送手机验证码
     * @param
     * @return
     **/
    @PostMapping("/sendMsg")
    public R<String> sendmsg(@RequestBody User user){
        //获取手机号
        String phone = user.getPhone();
        //判断手机号是否为空
        if (StringUtils.isNotEmpty(phone)){
            // 生成随机的4位验证码
            String integercode = ValidateCodeUtils.generateValidateCode(4).toString();
            // 调用阿里云提供的短信服务API完成发送短信
            /* SMSUtils.sendMessage("生活记录",
                    "SMS_209163022",
                    "15166664522",
                    "20220619");*/
            System.out.println(integercode);

           /* // 需要将生成的验证码保存到Session
            httpServletRequest.getSession().setAttribute(phone,integercode);*/

            //需要将生成的验证码保存到Redis,设置过期时间
            redisTemplate.opsForValue().set(phone,integercode,5, TimeUnit.MINUTES);

            return R.success("手机验证码短信发送成功");
        }
        return R.error("短信发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map ,HttpSession httpSession){
        log.info(map.toString());
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();

        /*//从Session中获取保存的验证码
        String sessioncode = request.getSession().getAttribute(phone).toString();*/

        //从Redis中获取缓存的验证码
        Object sessioncode =  redisTemplate.opsForValue().get(phone);

        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        if (sessioncode!=null&&sessioncode.equals(code)){
            //如果能够比对成功，说明登录成功
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            //根据手机号获取用户
            User one = userService.getOne(lqw);
            //判断用户是否存在
            if (one!=null){
                //存在
                httpSession.setAttribute("user",one.getId());
                //从Redis中删除缓存的验证码
                redisTemplate.delete(phone);

                return R.success(one);
            }
            //不存在
            one = new User();
            one.setPhone(phone);
            one.setStatus(1);
            userService.save(one);
        }
            return R.error("登录失败");
    }
}